<template>
<base-breadcrumb :title="titleName" class="topContainer">
  <div class="app-container">
    <div class="container" >
      <a-spin :spinning="progressing" :tip="progressingTips||'处理中...'">
      <a-card>

        <div class="button-bar">
        <title-name title="施工进度总计划"></title-name>
          <!-- <a-button type="primary" :disabled="type=='view'|| confirmLoadings || !selectedData"  @click="importFromTemplate()"   >导入模板</a-button>
          <a-button type="primary" :disabled="type=='view'|| confirmLoadings || !selectedData"  @click='addSameNode'   >新增同级节点</a-button>
          <a-button type="primary" :disabled="type=='view'|| confirmLoadings || !selectedData ||(selectedData.level===4)"  @click='addNextNode'  >新增下级节点</a-button>
          <a-button type="default" :disabled="type=='view'|| confirmLoadings || !selectedData ||(selectedData.nodeOrder=='0' || selectedData.nodeOrder=='2')"  @click="action('moveUp')"   >上移</a-button>
          <a-button type="default" :disabled="type=='view'|| confirmLoadings || !selectedData || (selectedData.nodeOrder=='1'|| selectedData.nodeOrder=='2')"  @click="action('moveDown')"   >下移</a-button>
          <a-button type="default" :disabled="type=='view'|| confirmLoadings || !selectedData || selectedData.level=='1'"  @click="action('outdent')"  >升级</a-button>
          <a-button type="default" :disabled="type=='view'|| confirmLoadings || !selectedData || selectedData.level=='4'"  @click="action('indent')" >降级</a-button>
          <a-button type="default" :disabled="type=='view'|| confirmLoadings || !selectedData"  @click="action('del')"  >删除节点</a-button> -->

          <a-button type="primary" @click="showDrawer()">查看甘特图</a-button>
          <div style="float:right">
            <!-- <a-button @click="saveDraft()" :disabled="type=='view'|| confirmLoadings || type=='approve' " type="primary" >保存草稿</a-button>
            <a-button @click="submitForm()" :disabled="type=='view'|| confirmLoadings || type=='approve' "      style="margin-left:12px" type="primary">提交</a-button> -->
            <!-- <a-button @click="goBack()" type="default" style="margin:0 12px">关闭</a-button> -->
          </div>
        </div>
        <!-- <a-button v-if="form.fileList" style="border:none;margin-bottom:10px"> -->
        <div style="border:none;margin-bottom:10px;margin-left:10px">
            <upload-list
              :businessCode="'PM12'"
              :editModel="2"
              :text="text"
              :showUpload.sync="isClose"
              :uploadArrys.sync="form.fileList"
              :projectId="projectId"></upload-list>
          </div>



          <div class="pub-table-select-count">
            <a-icon type="info-circle" theme="twoTone"/>
            <span style="margin-right: 12px">
              项目：<span class="totalNum">{{total.projectName }}   </span> |
              节点共 ：<span class="totalNum">{{total.nodeTotal|| 0  }} 项  </span> |
              一级节点共<span class="totalNum">{{ total.firstNodeNum || 0 }} 项  </span> |
              二级节点共<span class="totalNum">{{ total.secondNodeNum || 0 }} 项  </span> |
              三级节点共<span class="totalNum">{{ total.thirdNodeNum || 0 }} 项  </span> |
              周期天数<span class="totalNum">{{ total.duration }}   </span> |
              周期间隔<span class="totalNum">{{ total.intervalTime}} </span>
            </span>
          </div>
          <!-- <a-table  row-key="nodeId" :scroll="{ x: 800, y: 600 }" -->
        <div class="gantt-layout">
          <a-drawer
                  ref="ganttDrawer"
                  title=""
                  placement="right"
                  :closable="false"
                  :z-index="10"
                  :get-container="false"
                  :visible="visible"
                  :body-style="{padding:'0'}"
                  :wrap-style="{ position: 'absolute'}"
                  width="70%"
                  :after-visible-change="afterVisibleChange"
                  @close="onClose" >
            <gantt ref="ganttCom" class="left-container"
                   :columns="ganttColumns"
                   :plugins="plugins"
                   :tasks="tasks"
                   :heigh="ganttHeight"
                   @task-deleted="deleteTask"
                   @task-updated="logTaskUpdate"
                   @link-updated="logLinkUpdate"
                   @task-selected="selectTask">
            </gantt>
          </a-drawer>
        <a-table v-if="tableData && tableData.length" row-key="nodeId" :scroll="{ x: 800, y: 600 }"
                   ref="table"
                   :columns="columns"
                   :pagination="false"
                   :defaultExpandAllRows="false"
                   :expandIconColumnIndex="1"
                   @expand="rowExpand"
                   :indentSize="indentSize"
                   :data-source="tableData"
                   :rowClassName="rowClassNames"
                   :customRow="clickRow">
          <template slot="name" slot-scope="text, record, index">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </template>
          <template slot="businessMatters" slot-scope="text, record, index">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </template>
          <template slot="completeStandard" slot-scope="text, record, index">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </template>
          <template slot="verifyDoc" slot-scope="text, record, index">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </template>
          </a-table>
        </div>
      </a-card>
      </a-spin>

      <div style="float:right;" class="page-btn-right-top">
        <a-button type="primary" @click="goBack">关闭</a-button>
      </div>




    </div>
  </div>
  </base-breadcrumb>
</template>
<script>
  import {  Ellipsis } from '@/components'
  import { gantt } from 'dhtmlx-gantt'
  import {  getNodeControl} from '@/api/template'
  import { getProjects,getconstructionPlan , editPlan ,searchFiles, addDownNode ,submitAudit, addSameNode, editNodePosition, deleteWork ,importTemplate} from '@/api/construction/planInput'
  import Gantt from '../gantt/gantt'
  import TaskTemplateModal from '../gantt/template-modal'
  import locale from 'ant-design-vue/es/date-picker/locale/zh_CN'
  import * as moment from 'moment'
  import EditableCell from './EditableCell'
  import { getJobs } from '@/api/subassembly/TreeSelectOrganization';
  import { getOrganizePeopleList } from '@/api/commons'
  import UploadList from '../progress/file'
  import modal from '@/components/SelectJobs'
  import Vue from 'vue' // 第一责任人

  const columns =[
    {
      title: '编号',
      width: 60,
      dataIndex: 'index'
    },
    {
      title: '阶段/类别',
      align:'left',
      dataIndex: 'name',
      scopedSlots: { customRender: 'name' },
      width: 300,
    },
    {
      title: '业务事项',
      align:'center',
      dataIndex: 'businessMatters',
      width: 300,
      scopedSlots: { customRender: 'businessMatters' },
    },
    {
      title: '管控级别',
      align:'center',
      dataIndex: 'controlLevelName',
      scopedSlots: { customRender: 'controlLevelName' },
      width: 120
    },
    {
      title: '周期',
      dataIndex: 'duration',
      align:'center',
      width: 120,
      scopedSlots: { customRender: 'duration' },
    },
    {
      title: '计划开始时间',
      dataIndex: 'startTime',
      align:'center',
      width: 150,
      scopedSlots: { customRender: 'startTime' },
    },
    {
      title: '计划完成时间',
      dataIndex: 'endTime',
      align:'center',
      width: 120,
      scopedSlots: { customRender: 'endTime' },
    },
    {
      title: '完成标准',
      dataIndex: 'completeStandard',
      width: 300,
      align:'center',
      scopedSlots: { customRender: 'completeStandard' },
    },
    {
      title: '验证资料',
      dataIndex: 'verifyDoc',
      align:'center',
      width: 300,
      scopedSlots: { customRender: 'verifyDoc' },
    },
    {
      title: '第一责任人',
      align:'center',
      dataIndex: 'firstResponsible',
      width: 350,
      scopedSlots: { customRender: 'firstResponsible' },
    },
    {
      title: '直接责任人',
      width: 120,
      align:'center',
      dataIndex: 'directResPerName',
      scopedSlots: { customRender: 'directResPerName' },
    },
  ]
  export default {
    name: 'DhtmlxGantt',
    components: { Gantt, TaskTemplateModal ,EditableCell,UploadList,modal,Ellipsis},
      props: {
          isAudit: { // 是否作为审批详情
              type: Boolean,
              default: false
          }
      },
      watch: {
          isAudit: {
              immediate: true,
              handler(val) {
                  if (val) {
                      this.type = 'view'
                  }
              }
          }
      },
    data() {
      return {
        ganttData: { data: [] },
        isGanttDataOk: false,
        form:{
          fileList: [],
        },
        progressing:false,
        progressingTips:'处理中...',
        isClose:false,
        ganttHeight: 661,
        levelOption:'',
        disabled:false,
        uploadLists:[],
        tableData: [],
        titleName:'',
        startDates:'',
        indentSize:15,
        type:'',
        locale,
        tasks: { data: [], links: [] },
        columns,
        templateId:'',
        addLevel:'',
        bindOrgVisible:false,
        rowSelection: {},
        resultData:{},
        saveSelectRows:[],
        ganttColumns:[],
        preTasks: [],
        currentId:'',
        selectLevel:'',
        total:{},
        projectId:'',
        loading:false,
        text:'上传双代号网络图',
        responsLists:[],
        taskType: 'task',
        modalTitle: '新增节点',
        confirmLoading: false,
        nodeList:'',
        addVisible: false,
        visible:false,
        selectId:'',
        taskTemplateVisible: false,
        plugins: {
          undo: true,
          drag_timeline: true
        },
        messages: [],
        selectedTask: null,
        rangeConfig: {
          rules: [{ type: 'array', required: true, message: '请选择计划日期!' }]
        },
        today:'2020-11-23',
        confirmLoadings:false,
        selectedData:null,
         orgQuery: {}, //搜索组织树参数
         screening:true,
      }
    },
    beforeCreate() {
      this.form = this.$form.createForm(this, {})
    },
    created() {
      this.today = moment().format('yyyy-MM-DD')
      const userInfo = Vue.getAcloudProvider().getUserInfo()
      this.currentId = userInfo.id
      this.templateId = this.$route.query.planId||localStorage.getItem('currentSelectMasterPlanId')||this.$route.query.id
      // 如果是从审批页面过来，那么则直接获取url上的参数即可
      if(this.$route.query.type === 'approve') {
        this.templateId = this.$route.query.id
      }
      this.projectId = this.$route.query.projectId
      if(this.$route.fullPath=='/construction/addAdjustView'){
        this.type='view'
      }
      this.type = this.$route.query.type
      // setTimeout(()=>{
      //   this.getOrganizePeopleList()
      //   this.getNodeControl()
      //   this.searchFiles()
      // },2000)
      this.getconstructionPlan(true)
      localStorage.removeItem('task')
      localStorage.removeItem('link')
      this.tasks.data = []
      this.tasks.links = []
      this.ganttColumns = [
        {
          name: 'sortNum', label: '编号', align: 'center',resize:true,tree: false, width:40, template: function(obj) {
            return obj.$index + 1
          }
        },
        {
          name: 'name', label: '阶段/类别', align: 'left',resize:true,tree: false, width:140, template: function(obj) {
            return obj.text
          }
        }
      ]
      gantt.config.layout = {
        css: "gantt_container",
        cols: [
          {
            min_width: 140,
            width:140,
            rows:[
              {view: "grid", scrollX: "gridScroll", scrollable: true, scrollY: "scrollVer"},
              {view: "scrollbar", id: "gridScroll", group:"horizontal"}
            ]
          },
          {resizer: true, width: 1},
          {
            rows:[
              {view: "timeline", scrollX: "scrollHor", scrollY: "scrollVer"},
              {view: "scrollbar", id: "scrollHor", group:"horizontal"}
            ]
          },
          {view: "scrollbar", id: "scrollVer"}
        ]
      };
      
    gantt.config.date_format = '%Y-%m-%d'
    const cfg = gantt.config
    const strToDate = gantt.date.str_to_date(cfg.date_format, cfg.server_utc)
    gantt.templates.parse_date = function (date) {
      return strToDate(date)
    }
      // this.getJobs()
      console.log(this.tableData)
    },
    mounted(){
      console.log(this.tableData)
    },
    methods: {
      goBack() {   //关闭
        if(this.type == 'approve'){
          window.close()
        }else{
          this.$multiTab.close(this.$route.fullpath)
        }

      },
      // 第一责任人
      handleCancelBindOrg(val){
        // this.bindOrgVisible=val
      },
      handleCancelFirstRes(){
        this.bindOrgVisible = false
      },
      getProjects(id) {
            const params = {
                projectIds: [id],
            }
            getProjects(params).then((res) => {
              console.log( res.data )
                this.orgQuery.ids = res.data[0].orgId
            })
        },  
      handleBind(){
        this.bindOrgVisible = true
        this.form = {}
      },
      handleOk(value){
        this.bindOrgVisible = false
        let data={
          id:this.selectedData.nodeId,
          level:this.selectedData.level,
          firstResId:value.jobsSelectedId,
          firstResName:value.jobsSelectedName[0],
        }
        editPlan(data).then((res)=>{
          if(res){
            this.getconstructionPlan()
          }
        })
      },
      searchFiles(){
        searchFiles({businessId:this.projectId}).then(res =>{
          if(res.code == 200  && res.data.length != 0){
            this.form.fileList = res.data
          }
        })
      },
      getNodeControl(){
        getNodeControl().then((res)=>{
          this.nodeList = res.data
        })
      },
      renderGantt() {
      if (this.isGanttDataOk) {
        return
      }
      gantt.clearAll()
      console.log('zzzzz', this.ganttData)
      gantt.parse(this.ganttData)
      this.isGanttDataOk = true
    },
    buildGanttData(treeData, open) {
      const ganttData = {
        data: [],
      }
      const readTreeData = (children, parent) => {
        children.forEach((c) => {
          const data = { ...c, id: c.id, type: c.children ? 'project' : '', parent, open }
          ganttData.data.push(this.valuesToTask(data))
          if (c.children && c.children.length > 0) {
            readTreeData(c.children, c.id, open)
          }
        })
      }
      readTreeData(treeData, null, open)
      return ganttData
    },
      // renderGantt(treeData,open){
      //   gantt.clearAll()
      //   const ganttData = {
      //     data:[]
      //   }
      //   const readTreeData = (children,parent)=>{
      //     children.forEach(c=>{
      //        const data = {...c,id:c.nodeId,type:c.children?'project':'',parent,open}
      //        ganttData.data.push(this.valuesToTask(data))
      //        if(c.children&&c.children.length>0){
      //          readTreeData(c.children,c.nodeId,open)
      //        }
      //      })
      //   }
      //   readTreeData(treeData,null,open)
      //   gantt.parse(ganttData)
      // },

      // 获取模板
      getconstructionPlan(showLoading){
        if(showLoading){
          this.progressing=true
          this.progressingTips='总计划加载中...'
        }
        getconstructionPlan(this.templateId).then((res)=>{
          this.plugins = {}
          this.total = res.data
          this.projectId = res.data.projectId
            this.searchFiles()
          this.tableData = res.data.planDetailResultList||[]
          this.tableData.forEach(item1=>{
            if(item1.children){
              item1.children.forEach(item2=>{
                if(item2.children){
                  item2.children.forEach(item3=>{
                    if(item3.children){
                      item3.children.forEach(item4=>{
                        const area = {
                          label:item4.directResPerName,
                          key:item4.directResPerId
                        }
                        item4.directResPer=area
                      })
                    }
                  })
                }
              })
            }
          })
          this.ganttData = this.buildGanttData(this.tableData, true)
          this.progressing=false
          this.progressingTips=''
        }).catch(()=>{
          this.progressing=false
          this.progressingTips=''
        })
      // this.searchFiles()
      },
      // 点击行
      clickRow(record, index){
        const _this = this
        return {
          on: {
            click: () => {
              _this.selectId = record.nodeId
              _this.selectedData = record
              _this.rowClassNames(record)
              gantt.selectTask(record.nodeId)
            }
          }
        }
      },
      onClose(){
        this.visible=false
      },
      showDrawer() {
        this.visible = !this.visible
        this.renderGantt()
      },
      afterVisibleChange(visible){
        if(visible){
          gantt.refreshData()
        }
      },
      rowExpand(expanded, task){
        if(expanded){
          gantt.open(task.nodeId)
        }else{
          gantt.close(task.nodeId)
        }
      },
      getPopupContainer(triggerNode){
        return  triggerNode.parentNode
      },
      valuesToTask(values) {
        const _this = this
        return {
          id: values.id||values.nodeId,
          parent:values.parent,
          text: values.name||values.businessMatters,
          name: values.name,
          businessMatters: values.businessMatters,
          start_date: values.start_date||values.startTime||_this.today,
          startDate: values.startDate||values.startTime||_this.today,
          end_date: values.end_date||values.endTime||_this.today,
          endDate: values.endDate||values.endTime||_this.today,
          duration: values.duration,
          parentId: values.workPackId,
          type: values.type,
          preTask: values.preTask,
          matters: values.businessMatters,
          levelType: values.levelType,
          responsible: values.responsible,
          firstResponsible: values.firstResponsible,
          level:values.level,
          nodeId:values.nodeId,
          workPackId:values.workPackId,
          open:values.open
        }
      },

      selectTask: function(task) {
        console.log('当前选中行数据:', task)
        this.selectedTask = task
        // gantt.selectTask(task.id);
      },
      deleteTask: function(taskId) {
        console.log('当前删除的数据：', taskId)
        this.selectedTask = task
        gantt.deleteTask(task.id);
      },
      addMessage(message) {
        // let _this = this
        // _this.messages.unshift(message)
        // if (_this.messages.length > 40) {
        //   _this.messages.pop()
        // }
      },
      logTaskUpdate(id, mode, task) {
        const text = (task && task.text ? ` (${task.text})` : '')
        const message = `Task ${mode}: ${id} ${text}`
        this.addMessage(message)
      },
      rowClassNames(record){
        if( this.selectId == record.nodeId ){
          return 'clickRowStyle'
        }
      },
      logLinkUpdate(id, mode, link) {
        let message = `Link ${mode}: ${id}`
        if (link) {
          message += ` ( source: ${link.source}, target: ${link.target} )`
        }
        this.addMessage(message)
      },

    }
  }
</script>

<style scoped>
  html, body {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  /deep/ .ant-table-body  .clickRowStyle{
    background-color: rgb(230, 243, 252);
  }
  /deep/ .ant-pro-basicLayout-children-content-wrap{
    flex:1;
  }
  .gantt-layout{
    position: relative;
  }
  /deep/ .ant-table-thead th{
    height: 60px;
    line-height: 60px;
    padding: 0;
  }
  /deep/ .ant-table-placeholder{
    height: 600px;
  }
  /deep/ .gantt-layout .ant-table-body{
    min-height: 600px;
  }
  /deep/ .ant-drawer-content-wrapper{
    box-shadow: none !important;
  }
  /deep/ .ant-table-selection-column{
    width:40px;
  }

  .button-bar {
    margin-bottom: 10px;
    /* position:fixed;
    top:200px; */
  }

  .button-bar > button:not(:first-child) {
    margin-left: 10px;
  }
  /deep/ .ant-modal-body{
    padding:0
  }
  /*  /deep/ input[type='text'], input[type='password'], input[type='number'], textarea{*/
  /*      border:none*/
  /*  }*/
  /*  /deep/ .ant-calendar-picker-input.ant-input{*/
  /*      width:130px;*/
  /*      border:none*/
  /*  }*/
  /*/deep/ .ant-select-selection--single{*/
  /*    border:none*/
  /*}*/
  /*/deep/ input{*/
  /*     touch-action: manipulation;*/
  /*     border: none;*/
  /*     width: 70px*/
  /* }*/
  td{
    display:flex;
  }
    /deep/ .ant-select:not(.ant-pagination-options-size-changer) .ant-select-selection, .ant-input-number{
    height:28px !important;
}
  /deep/ .ant-select-selection,.ant-input-number{
    height:28px !important;
  }

  input[type='text'], input[type='password'], input[type='number'], textarea {
      height:28px
  }
  .ant-calendar-picker{
      width:100%;height:28px
  }
  .ant-cascader-picker{
      width:100%;height:28px
  }
  form .ant-select, form .ant-cascader-picker{
      width:100%;height:28px
  }
  /deep/ .ant-calendar-picker-input.ant-input{
      width:100%;height:28px
  }
  /* .topContainer{
    position: relative;
  } */
</style>
